package Server.controller;

import Plug.operLog.OperLog;
import Plug.result.RetResponse;
import Plug.result.RetResult;
import Server.dao.InviteUsersDao;
import Server.dao.SaleDao;
import Server.dao.UsersDao;
import Server.dao.UsersSaleDao;
import Server.entity.*;
import Server.tool.BeanToJson;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.tomcat.jni.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@RestController
@RequestMapping("SaleController")
public class SaleController {
    @Autowired
    private SaleDao saleDao;
    @Autowired
    private UsersSaleDao usersSaleDao;
    @Autowired
    private InviteUsersDao inviteUsersDao;
    @Autowired
    private UsersDao usersDao;
    @PersistenceContext
    EntityManager entityManager;
    @RequestMapping("List")
    public RetResult ClassList(@RequestBody JSONObject jsonObject) {
        Sale entity = (Sale) BeanToJson.jsonTobean(jsonObject.getJSONObject("common").toString(), Sale.class);
        int page = Integer.parseInt(jsonObject.getString("page")) - 1;
        int size = Integer.parseInt(jsonObject.getString("limit"));
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "uuid");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<Sale> example = Example.of(entity, matcher);
        Page<Sale> userlist = saleDao.findAll(example, pageable);
        return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int) userlist.getTotalElements());
    }

    @RequestMapping("UserList")
    public RetResult UserList(@RequestBody JSONObject jsonObject) {
        UsersSale entity = (UsersSale) BeanToJson.jsonTobean(jsonObject.getJSONObject("common").toString(), UsersSale.class);
        int page = Integer.parseInt(jsonObject.getString("page")) - 1;
        int size = Integer.parseInt(jsonObject.getString("limit"));
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "uuid");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("sale.name", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("users.name", ExampleMatcher.GenericPropertyMatchers.contains());
        Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        fspuser=usersDao.findByUuid(fspuser.getUuid());
        if (fspuser.getRole().getUuid().equals("2")) {

            /*entity.setUsers(usersDao.findByUuid(fspuser.getUuid()));
            Example<UsersSale> example = Example.of(entity);
            Page<UsersSale> userlist = usersSaleDao.findAll(example, pageable);*/
            /*if(fspuser.getRole().getUuid().equals("2")){
                            }else{
                *//*String sql="";
                if(entity.getSale()==null||StringUtils.isEmpty(entity.getSale().getName())){
                    sql =" select * from users_sale where 1=1 and user_id in (select invite_id from invite_users where user_id = '"+fspuser.getUuid()+"') limit "+page+","+size;
                }else{
                    sql =" select * from users_sale where 1=1 and user_id in (select invite_id from invite_users where user_id = '"+fspuser.getUuid()+"') AND sale_id in (select uuid from sale where name like '%"+entity.getSale().getName()+"%')limit "+page+","+size;
                }
                List<ShopOrder> ls = entityManager.createNativeQuery(sql, ShopOrder.class).getResultList();
                return RetResponse.makeRsp(0, "成功", ls, (int) ls.size());
*//*
            }*/
            String sql="";
            if(entity.getSale()==null||StringUtils.isEmpty(entity.getSale().getName())){
                sql =" select * from users_sale where 1=1 and user_id in (select invite_id from invite_users where user_id = '"+fspuser.getUuid()+"') limit "+page+","+size;
            }else{
                sql =" select * from users_sale where 1=1 and user_id in (select invite_id from invite_users where user_id = '"+fspuser.getUuid()+"') AND sale_id in (select uuid from sale where name like '%"+entity.getSale().getName()+"%')limit "+page+","+size;
            }
            List<ShopOrder> ls = entityManager.createNativeQuery(sql, ShopOrder.class).getResultList();
            return RetResponse.makeRsp(0, "成功", ls, (int) ls.size());


        } else {
            if (fspuser.getRole().getUuid().equals("3")){
                entity.setUsers(fspuser);
            }
            Example<UsersSale> example = Example.of(entity, matcher);
            Page<UsersSale> userlist = usersSaleDao.findAll(example, pageable);
            return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int) userlist.getTotalElements());

        }

    }

    @OperLog("优惠券新增修改")
    @RequestMapping("Save")
    public RetResult Save(@RequestBody Sale entity) {
        if (StringUtils.isEmpty(entity.getUuid())) {
            entity.setStatus(Sale.Status.ING);
        } else {
            entity.setStatus(saleDao.findByUuid(entity.getUuid()).getStatus());
        }
        saleDao.save(entity);
        return RetResponse.makeOKRsp();
    }

    @OperLog("优惠券激活过期")
    @RequestMapping("Del")
    public RetResult Del(@RequestBody Sale entity) {
        entity = saleDao.findByUuid(entity.getUuid());
        if (entity.getStatus().equals(Sale.Status.NO)) {
            entity.setStatus(Sale.Status.ING);
        } else {
            entity.setStatus(Sale.Status.NO);
        }
        saleDao.save(entity);
        return RetResponse.makeOKRsp();
    }

    @OperLog("用户优惠券激活过期")
    @RequestMapping("UserDel")
    public RetResult UserDel(@RequestBody UsersSale entity) {
        entity = usersSaleDao.findByUuid(entity.getUuid());
        if (entity.getStatus().equals(UsersSale.Status.NO)) {
            entity.setStatus(UsersSale.Status.ING);
        } else {
            entity.setStatus(UsersSale.Status.NO);
        }
        usersSaleDao.save(entity);
        return RetResponse.makeOKRsp();
    }

    @RequestMapping("GetSale")
    public RetResult GetSale(@RequestBody Sale sale) {
        return RetResponse.makeOKRsp(saleDao.findByUuid(sale.getUuid()));
    }

    @OperLog("赠送优惠券")
    @Transactional
    @RequestMapping("UserSave")
    public RetResult UserSave(@RequestBody JSONObject jsonObject) {
        try {
            Sale entity = (Sale) BeanToJson.jsonTobean(jsonObject.getJSONObject("sale").toString(), Sale.class);
            entity = saleDao.findByUuid(entity.getUuid());
            entity.setNumber(entity.getNumber() - 1);
            if(entity.getNumber() - 1<0){
                return RetResponse.makeErrRsp("优惠券不足");
            }
            saleDao.save(entity);
            Users user = (Users) BeanToJson.jsonTobean(jsonObject.getJSONObject("user").toString(), Users.class);
            user = usersDao.findByUuid(user.getUuid());
            Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
            if(!fspuser.getRole().getUuid().equals("1")){
                fspuser=usersDao.findByUuid(fspuser.getUuid());
                InviteUsers inc=inviteUsersDao.findByUsersAndInviteUser(fspuser,user);
                if(inc==null){
                    return RetResponse.makeErrRsp("这不是你的客户不能赠送");
                }
            }
            UsersSale usersSale = new UsersSale();
            usersSale.setSale(entity);
            usersSale.setUsers(user);
            usersSale.setStatus(UsersSale.Status.ING);
            usersSaleDao.save(usersSale);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RetResponse.makeErrRsp("失败");
        }
        return RetResponse.makeOKRsp();
    }
}
